﻿using CSRedis;
using furion.blog.Application.Contracts;
using furion.blog.Domain.MySQL;
using Furion;
using Furion.TaskScheduler;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.Web.Core.Jobs
{
    /// <summary>
    /// 写入日志操作
    /// </summary>
    public class RequestLogJobWorker : ISpareTimeWorker
    {
        private Stopwatch _stopwatch;
        private CSRedisClient[] _csredis;
        private IRequestLogService _requestLogService;

        /*public RequestLogJobWorker(CSRedisClient[] csredis,IRequestLogService requestLogService) {
            this._csredis = csredis;
            this._requestLogService = requestLogService;
        }*/

        [SpareTime(3000, "redisLogSaveToMySQL", DoOnce = false, StartNow = true, ExecuteType = SpareTimeExecuteTypes.Serial)]
        public async void DoSomething(SpareTimer timer, long count)
        {
            this._csredis = App.GetService<CSRedisClient[]>();
            this._requestLogService = App.GetService<IRequestLogService>();

            _stopwatch = new Stopwatch();
            _stopwatch.Start();
            long MAX_COUNT = 1000L;//每次最多写入一千条
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Console.WriteLine("开始执行操作日志写入MySQL>>>>>>>" + time);
            long itemCount = this._csredis[14].LLen("RequestLog");
            string[] items = null;
            List<RequestLog> saves = null;
            MAX_COUNT = itemCount >= MAX_COUNT ? MAX_COUNT : itemCount;
            if (MAX_COUNT > 0L)
            {
                saves = new List<RequestLog>();
                for (int i = 0; i < MAX_COUNT; i++)
                {
                    saves.Add(InitItem(await this._csredis[14].LPopAsync<string>("RequestLog")));
                }
                //进行保存
                await this._requestLogService.Save(saves);
            }
            long usedTime = 0L;
            if (_stopwatch != null)
            {
                _stopwatch.Stop();
                usedTime = _stopwatch.ElapsedMilliseconds;
            }
            
            _stopwatch = null;
            Console.WriteLine("结束执行操作日志写入MySQL>>>>>>>" + time + ",耗时：" + usedTime + "ms");
        }

        /// <summary>
        /// 把字符串数据转换为实例
        /// </summary>
        /// <param name="itemInfo"></param>
        /// <returns></returns>
        private RequestLog InitItem(string itemInfo)
        {
            RequestLog obj = JsonConvert.DeserializeObject<RequestLog>(itemInfo);
            return obj;
        }


    }
}
